package com.haiyi.activiti.engine.framework.template.freemarker;

import com.haiyi.activiti.engine.model.entity.FormModel;
import com.haiyi.activiti.engine.framework.activiti.manager.TaskManager;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

/**
 * <p> </p>
 *
 * <pre> Created: 2018/12/10 14:24 </pre>
 *
 * @author hlu
 * @version 1.0
 * @since JDK 1.7
 */
public abstract class AbstractFreemarkerBuilderAdapter implements FreemarkerBuilderAdapter{
    @Autowired
    private TaskManager taskManager;

    @Override
    public void resolverFormModelJson(FormModel formModel,Task task) {
        if(formModel.getComponentDesign()==null || StringUtils.isBlank(formModel.getComponentDesign().getFormObj())){
            return;
        }

        FreemarkerBuilder freemarkerBuilder = new FreemarkerBuilder();

        /**
         * 获取之前提交的参数
         */
        final Map<String, Object> processParams = taskManager.getParams(task.getId());
        freemarkerBuilder.setProcessParams(processParams);


        buildParams(formModel,task,freemarkerBuilder);
        final Map<String, Object> params = getParams(freemarkerBuilder);
        final String result = resolver(formModel, params);
        formModel.getComponentDesign().setFormObj(result);
    }

    /**
     * 构建模板所有的参数,包含内置参数，内置对象
     * @param formModel
     * @param task
     * @param freemarkerBuilder
     */
    protected abstract void buildParams(FormModel formModel, Task task, FreemarkerBuilder freemarkerBuilder);


    /**
     * 获取最终的参数集合，考虑不同作用域下的相同变量的情况，根据优先级合并
     * @param freemarkerBuilder
     * @return
     */
    protected abstract Map<String, Object> getParams(FreemarkerBuilder freemarkerBuilder);

    /**
     * 解析模板json,返回最终的json
     * @param formModel
     * @param params
     * @return
     */
    protected abstract String resolver(FormModel formModel, Map<String, Object> params);


}
